//
//  UserAccount.swift
//  weibo19
//
//  Created by Arvin on 15/11/10.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    // 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    // access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    // access_token的过期日期
    var expires_date: NSDate?
    // 当前授权用户的UID
    var uid: String?
    // 友好显示名称
    var name: String?
    // 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    // 1归档 解档
    // 1.1 归档
    func saveAccount() {
        // 沙盒路径
        let filename = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString) .stringByAppendingPathComponent("account.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: filename)
    }
    // 1.2 解当
    class func loadAccount() -> UserAccount? {
        let filename = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString) .stringByAppendingPathComponent("account.plist")
        let account =  NSKeyedUnarchiver.unarchiveObjectWithFile(filename) as? UserAccount
        // 判断token是否过期
        let result =  account?.expires_date?.compare(NSDate())
        // OrderedDescending 降序 expires_ > 当前日期 如果不等于降序, 说明账号过期
        if result != NSComparisonResult.OrderedDescending {
            return nil
        }
        return account
    }
    
    init(dict: [String: AnyObject]) {
        // KVC前要先初始化对象
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    // 过滤多余的键值
    override  func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    // 重写description方法, 打印对象属性信息
    override var description: String {
        let keys = ["access_token", "expires_in", "uid", "name", "expires_date", "avatar_large"]
        let dict = dictionaryWithValuesForKeys(keys)
        return dict.description
    }
    
    // 编码 解码
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init()
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
}
